#!/bin/bash

TOP=`pwd`
PATCH_DIR=patches
PATCH_NAME=PATCHES
#TAG_PATCH=echo "build-patch_`date`"|sed "s/ /_/g"|sed "s/:/-/g"
TAG_PATCH="build-patch-start"
NUM=0
PROJECT_PATH=`echo $1 | sed "s/\/$//"`

if [ ! -n "$PROJECT_PATH" ] ; then
	echo "Please input the directory of source code"
	echo "e.g. ./apply-patches.sh android-ginerbread"
	exit
fi

if [ 1 -eq 0 ] ; then
	#check the first parameter
	if [ ! -n "$PROJECT_PATH" ]; then
		echo "please input name of tar file."
		echo "e.g. ./apply-patches.sh sample.tar"
		exit
	fi
fi

#if patches folder exist and it's empty, then ignore it.
#otherwise show error.
NUM=`ls -1a ${TOP}/$PROJECT_PATH/${PATCH_DIR} 2>/dev/null | wc -l`
if [ ${NUM} -gt 0 ]; then
	echo "WARNING: \"patches\" folder exist Remove it ... "
	sleep 1
	rm -rf ${TOP}/$PROJECT_PATH/${PATCH_DIR}
fi

mkdir ${TOP}/$PROJECT_PATH/${PATCH_DIR}

set -e

# remove useless source codes
cd ${TOP}/$PROJECT_PATH

rm -rf device/intel/PRIVATE/release

rm -rf vendor/intel/PRIVATE

rm -rf device/htc
rm -rf device/samsung

rm -rf hardware/intel/PRIVATE/tiwl1283/proprietary/vbox
rm -rf hardware/intel/PRIVATE/tiwl1283/include
rm -rf hardware/intel/PRIVATE/pvr/proprietary/vbox
rm -rf hardware/intel/PRIVATE/psb_video/vbox
rm -rf hardware/intel/PRIVATE/libmix/proprietary/vbox
rm -rf hardware/intel/PRIVATE/libadvci/proprietary
rm -rf hardware/intel/PRIVATE/hw_ssl/proprietary
rm -rf device/intel/PRIVATE/sw_codecs_audio/proprietary
rm -rf device/intel/PRIVATE/ipp/proprietary

rm build.201103151133.andr.log
rm build-20110315-manifest.xml

# delete several projects removed since intel-alpha2
rm -rf device/intel/sreadahead
rm -rf device/intel/sw_codecs_video
rm -rf packages/apps/TippyTipper

tar -xf ${TOP}/${PATCH_NAME}.tar -C ${TOP}/$PROJECT_PATH

cd ${TOP}/$PROJECT_PATH/${PATCH_DIR}

for DIR in `find . -type d` ; do
	pushd ${DIR} > /dev/null
	NUM=`ls -1 *.patch 2> /dev/null | wc -l `
	if [ "${NUM}" != "0" ]; then
		echo "applying patches in ${DIR}"

		set +e
		mkdir ${TOP}/$PROJECT_PATH/${DIR} 2>/dev/null
		cd ${TOP}/$PROJECT_PATH/${DIR}
		set -e

		# repo leaves git repositories in a strange state... this is a fixup
		#git reset --hard HEAD
		#rm -rf .git/rebase-apply .git/packed-refs .git/rr-cache .git/svn
		# laydown tag
		#git tag -f ${TAG_PATCH}
		# apply patches, suppress any user local whitespace settings like strip-
		# screws up any prebuilt/binaries imported
		#ls -1 ${TOP}/$PROJECT_PATH/${PATCH_DIR}/${DIR}/*.patch | xargs -i git am --whitespace=nowarn {}

		# apply patches, including binary changes
		pwd
		#ls -1 ${TOP}/$PROJECT_PATH/${PATCH_DIR}/${DIR}/*.patch | xargs -i echo {}
		ls -1 ${TOP}/$PROJECT_PATH/${PATCH_DIR}/${DIR}/*.patch | xargs -i git apply --whitespace=nowarn {}
		echo ""

		#pwd
		#ls -1 ${TOP}/$PROJECT_PATH/${PATCH_DIR}/${DIR}/*.patch | xargs -i cat {} | patch -Np1
		#echo ""
	fi
	popd > /dev/null
done


echo ""
echo "apply all patches successfully."

